package com.unsiv.torch;

import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;

/**
 * <p>
 * screen program
 * </p>
 * 
 * @author fanzhen
 * @time 11:09:28 PM Sep 8, 2011
 * @email fanzhen.meng@gmail.com
 */
public class Program extends Activity {
	private Button program_switch;
	private ImageView ibutton_information;
	private ImageView ibutton_help;
	private Button program_finish;
	private ImageView ibutton_add;
	private Gallery gallery;
	private SeekBar sb;// haha..
	private TextView sb_start;
	private TextView sb_end;
	private TextView sb_progress;
	private SharedPreferences setting;
	private SharedPreferences mode;
	private Editor modelEditor;
	private ModelAdapter ma;
	private String type;
	private boolean newcustom;
	private int currentModeId;
	private AdView adView;
	private GoogleAnalyticsTracker tracker;
	private ImageView tap;
//	private boolean tapstatus = false;
	private long lastTapTime;
//	private long tapperiod;
	private long countStart;
	private long countEnd;
	private String tapValue = "customize";
	// private LinearLayout mylayout;
	// private Resources myColor;
	private LinearLayout line002;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.program);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.window_title);
		ImageView window_title = (ImageView) findViewById(R.id.window_title_name);
		window_title.setBackgroundResource(R.drawable.title_programming);

		// Obtain the tracker singleton
		tracker = GoogleAnalyticsTracker.getInstance();
		// Start the tracker in manual dispatch mode...
		tracker.startNewSession("UA-15519067-4", this);
		// ...alternatively, the tracker can be started with a dispatch interval
		// (in seconds).
		// tracker.startNewSession("UA-YOUR-ACCOUNT-HERE", 20, this);
		// // Create the adView
		adView = (AdView) findViewById(R.id.adView);
		// // Initiate a generic request to load it with an ad
		adView.loadAd(new AdRequest());
		setting = getSharedPreferences("setting", 0);
		line002 = (LinearLayout) findViewById(R.id.line002);
		tap = (ImageView) findViewById(R.id.tap);
		program_switch = (Button) findViewById(R.id.program_switch);
		Intent intent = getIntent();
		type = intent.getStringExtra("type");
		newcustom = intent.getBooleanExtra("newcustom", false);
		if ("led".equalsIgnoreCase(type)) {
			program_switch.setBackgroundResource(R.drawable.led);
			mode = getSharedPreferences("led_mode", 0);
			currentModeId = setting.getInt("current_led_mode", 1);
		} else {
			program_switch.setBackgroundResource(R.drawable.screen);
			mode = getSharedPreferences("screen_mode", 0);
			currentModeId = setting.getInt("current_screen_mode", 1);
		}
		modelEditor = mode.edit();
		gallery = (Gallery) findViewById(R.id.gallery);
		ma = new ModelAdapter();
		gallery.setAdapter(ma);
		ibutton_add = (ImageView) findViewById(R.id.model_plus);
		sb = (SeekBar) findViewById(R.id.program_seekbar);
		sb_start = (TextView) findViewById(R.id.sb_start);
		sb_end = (TextView) findViewById(R.id.sb_end);
		sb_progress = (TextView) findViewById(R.id.sb_progress);
		gallery.setSelection(currentModeId - 1);
		String value = mode.getString(String.valueOf(currentModeId), "");
		String values[] = value.split(",");
		if ("brightness".equals(values[0])) {
			sb_start.setText("5%");
			sb_end.setText("100%");
			sb_progress.setText(values[1]);
			sb.setMax(95);
			sb.setProgress(Integer.parseInt(values[1]) - 5);
		}
		if ("strobe".equals(values[0])) {
			sb_start.setText("0.5HZ");
			sb_end.setText("20HZ");
			sb_progress
					.setText(String.valueOf((Float.valueOf(values[1]) + 5) / 10));
			sb.setMax(195);
			sb.setProgress(Integer.valueOf(values[1]));
		}
		if ("customize".equals(values[0])) {
			line002.setVisibility(View.INVISIBLE);
			tap.setVisibility(View.VISIBLE);
		}
		sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(SeekBar sb) {
				int position = gallery.getSelectedItemPosition();
				String value = mode.getString(String.valueOf(position + 1), "");
				String values[] = value.split(",");
				if (values.length == 2 && !"customize".equals(values[0])) {
					if ("brightness".equals(values[0])) {
						sb_progress.setText(String.valueOf(sb.getProgress() + 5));
						modelEditor.putString(
								String.valueOf(position + 1),
								values[0] + ","
										+ String.valueOf(sb.getProgress() + 5));
					} else {
						sb_progress.setText(String.valueOf((float) (sb
								.getProgress() + 5) / 10));
						modelEditor.putString(
								String.valueOf(position + 1),
								values[0] + ","
										+ String.valueOf(sb.getProgress()));
					}
					modelEditor.commit();
					ma = new ModelAdapter();
					gallery.setAdapter(ma);
					ma.notifyDataSetChanged();
					gallery.setSelection(position);
				}
			}

			@Override
			public void onStartTrackingTouch(SeekBar sb) {
			}

			@Override
			public void onProgressChanged(SeekBar sb, int progress,
					boolean fromTouch) {
			}
		});
		tap.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View view, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					countStart =  System.currentTimeMillis();
					if("led".equalsIgnoreCase(type)){
						MyCamaraHelper.turnOn();
						tap.setBackgroundResource(R.drawable.tap_light);
					}else{
						tap.setBackgroundResource(R.drawable.tap_light);
					}
					break;
				case MotionEvent.ACTION_UP:
					if("led".equalsIgnoreCase(type)){
						MyCamaraHelper.turnOff();
						tap.setBackgroundResource(R.drawable.tap);
					}else{
						tap.setBackgroundResource(R.drawable.tap);
					}
					countEnd =  System.currentTimeMillis();
					if(countStart>0){
						long light_tapperiod = countEnd - countStart;
						tapValue = tapValue +"," + light_tapperiod;
					}
					if(lastTapTime>0){
						long black_tapperiod = countStart - lastTapTime;
						tapValue = tapValue +"," + black_tapperiod;
					}
					lastTapTime = countEnd;
				default:
					break;
				}
				return true;
			}
		});
//		tap.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View arg0) {
//				long current = System.currentTimeMillis();
//				tapperiod = current - lastTapTime;
//				if (lastTapTime > 0) {
//					tapValue = tapValue + "," + tapperiod;
//				}
//				lastTapTime = current;
//				if ("led".equalsIgnoreCase(type)) {
//					if (tapstatus) {
//						MyCamaraHelper.turnOff();
//						tap.setBackgroundResource(R.drawable.tap);
//						tapstatus = false;
//					} else {
//						MyCamaraHelper.turnOn();
//						tap.setBackgroundResource(R.drawable.tap_light);
//						tapstatus = true;
//					}
//				} else {
//					if (tapstatus) {
//						// setColor(R.color.black);
//						tap.setBackgroundResource(R.drawable.tap);
//						tapstatus = false;
//					} else {
//						// setColor(R.color.white);
//						tap.setBackgroundResource(R.drawable.tap_light);
//						tapstatus = true;
//					}
//				}
//			}
//		});
		ibutton_information = (ImageView) findViewById(R.id.program_information);
		ibutton_help = (ImageView) findViewById(R.id.program_help);
		program_finish = (Button) findViewById(R.id.program_finish);
		program_switch.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(Program.this, Program.class);
				if ("led".equalsIgnoreCase(type)) {
					intent.putExtra("type", "screen");
				} else {
					boolean supportTorch = MyCamaraHelper.checkCamera();
					if (supportTorch) {
						intent.putExtra("type", "led");
					}
				}
				startActivity(intent);
			}
		});
		gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View view,
					int position, long id) {
				String value = mode.getString(String.valueOf(position + 1), "");
				String values[] = value.split(",");
				if ("brightness".equals(values[0])) {
					line002.setVisibility(View.VISIBLE);
					tap.setVisibility(View.INVISIBLE);
					sb_start.setText("5%");
					sb_end.setText("100%");
					sb_progress.setText(values[1] + "%");
					sb.setMax(95);
					sb.setProgress(Integer.parseInt(values[1]) - 5);
				}
				if ("strobe".equals(values[0])) {
					line002.setVisibility(View.VISIBLE);
					tap.setVisibility(View.INVISIBLE);
					sb_start.setText("0.5HZ");
					sb_end.setText("20HZ");
					sb_progress.setText(String.valueOf((Float
							.valueOf(values[1]) + 5) / 10) + "HZ");
					sb.setMax(195);
					sb.setProgress(Integer.valueOf(values[1]));
				}
				if ("customize".equals(values[0])) {
					line002.setVisibility(View.INVISIBLE);
					tap.setVisibility(View.VISIBLE);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				Log.i("Program", "onNothingSelected");
			}
		});
		gallery.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long id) {
				Intent intent = new Intent(getApplication(), EditPannel.class);
				intent.putExtra("type", type);
				intent.putExtra("mode_id", String.valueOf(position + 1));
				startActivity(intent);
			}
		});
		gallery.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View view,
					final int position, long id) {
				new AlertDialog.Builder(Program.this)
						.setTitle("warning")
						.setMessage("confirm to delete this model?")
						.setIcon(android.R.drawable.ic_dialog_alert)
						.setPositiveButton("yes",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										modelEditor.remove(String
												.valueOf(position + 1));
										modelEditor.commit();
										Map<String, ?> models = mode.getAll();
										int count = models.size();
										for (Map.Entry<String, ?> entry : models
												.entrySet()) {
											String key = entry.getKey();
											String value = (String) entry
													.getValue();
											Log.i("program", key + ":" + value);
											if (position + 1 > 0
													&& Integer.parseInt(key) > position + 1) {
												modelEditor.putString(
														String.valueOf(Integer
																.parseInt(key) - 1),
														value);
											}
										}
										modelEditor.remove(String
												.valueOf(count + 1));
										modelEditor.commit();
										String value = mode.getString(
												String.valueOf(position + 1),
												"");
										String values[] = value.split(",");
										if ("brightness".equals(values[0])) {
											sb_start.setText("5%");
											sb_end.setText("100%");
											sb_progress.setText(values[1]);
											sb.setMax(95);
											sb.setProgress(Integer
													.parseInt(values[1]) - 5);
										}
										if ("strobe".equals(values[0])) {
											sb_start.setText("0.5HZ");
											sb_end.setText("20HZ");
											sb_progress.setText(String.valueOf((Float
													.valueOf(values[1]) + 5) / 10));
											sb.setMax(195);
											sb.setProgress(Integer
													.parseInt(values[1]));
										}
										ma = new ModelAdapter();
										gallery.setAdapter(ma);
										ma.notifyDataSetChanged();
										gallery.setSelection(position);
									}
								}).setNegativeButton("no", null).show();
				return true;
			}
		});
		ibutton_add.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(getApplication(), EditPannel.class);
				intent.putExtra("type", type);
				startActivity(intent);
			}
		});
		program_finish.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				int position = gallery.getSelectedItemPosition();
				String value = mode.getString(String.valueOf(position + 1), "");
				String values[] = value.split(",");
				if (!newcustom && "customize".equals(values[0])) {
					String[] tapValues = tapValue.split(",");
					if(tapValues.length>1){
						modelEditor.putString(String.valueOf(position + 1),tapValue);
						modelEditor.commit();
						ma = new ModelAdapter();
						gallery.setAdapter(ma);
						ma.notifyDataSetChanged();
						gallery.setSelection(position);
						tapValue = "customize";
					}
				}
				if ("led".equalsIgnoreCase(type)) {
					Intent intent = new Intent();
					intent.setClass(Program.this, LedTorch.class);
					startActivity(intent);
				} else {
					Intent intent = new Intent();
					intent.setClass(Program.this, ScreenTorch.class);
					startActivity(intent);
				}
			}
		});
		ibutton_information.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getApplication(), Information.class);
				startActivity(intent);
			}
		});
		ibutton_help.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getApplication(), Help.class);
				startActivity(intent);
			}
		});
	}

	private class ModelAdapter extends BaseAdapter {
		Map<String, ?> modes = mode.getAll();

		@Override
		public int getCount() {
			return modes.size();
		}

		@Override
		public Object getItem(int position) {
			return mode.getString(String.valueOf(position + 1), "");
		}

		@Override
		public long getItemId(int position) {
			return position + 1;
		}

		@Override
		public View getView(int position, View view, ViewGroup viewGroup) {
			LayoutInflater inflater = ((Activity) viewGroup.getContext())
					.getLayoutInflater();
			view = (RelativeLayout) inflater.inflate(R.layout.gallery_item,
					viewGroup, false);
			TextView text = (TextView) view
					.findViewById(R.id.gallery_item_name);
			TextView itemvalue = (TextView) view
					.findViewById(R.id.gallery_item_value);
			String value = mode.getString(String.valueOf(position + 1), "");
			// int selectedItem = gallery.getSelectedItemPosition();
			if (!"".equals(value)) {
				String values[] = value.split(",");
				if ("brightness".equals(values[0])) {
					// if(selectedItem==position){
					// text.setBackgroundResource(R.drawable.program_brightness);
					// text.setText("");
					// }else{
					text.setText("Brightness");
					// }
					itemvalue.setText(values[1] + "%");
				}
				if ("strobe".equals(values[0])) {
					// if(selectedItem==position){
					// text.setBackgroundResource(R.drawable.program_strobe);
					// text.setText("");
					// }else{
					text.setText("Strobe");
					// }
					itemvalue
							.setText(String.valueOf((Float.valueOf(values[1]) + 5) / 10)
									+ "HZ");
				}
				if ("customize".equals(values[0])) {
					// if(selectedItem==position){
					// text.setBackgroundResource(R.drawable.program_customize);
					// text.setText("");
					// }else{
					text.setText("Customize");
					// }
					itemvalue.setText(values.length - 1 + "times");
				}
			}
			return view;
		}
	}

	// private void setColor(int color_1) {
	// myColor = getBaseContext().getResources();
	// Drawable color_M = myColor.getDrawable(color_1);
	// mylayout.setBackgroundDrawable(color_M);
	// }
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "Exit");
		return true;
	}
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			MyCamaraHelper.turnOff();
			new ActivityUtil(this).exit();
			return true;
		}
		return false;
	}
}